import CryptoJS from 'crypto-js/crypto-js';
import tool from "@/utils/tool";

export const encrypt = (text) => {
  const key = tool.randomString(16);
  const sha = tool.randomString(16);
  const encrypt = encryptWith(text, key);
  const md5 = CryptoJS.MD5(sha + encrypt + key).toString();
  return sha + md5.substring(0, 16) + key + md5.substring(16) + encrypt;
}

export const encryptWith = (text, key) => {
  if (!text) return null;

  const uKey = CryptoJS.enc.Utf8.parse(key);
  const uText = CryptoJS.enc.Utf8.parse(text);
  const iv = CryptoJS.enc.Utf8.parse();
  const encrypt = CryptoJS.AES.encrypt(uText, uKey, {
    iv: iv,
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  return encrypt.toString();
}

export const decrypt = (text) => {
  if (text == null || text.length <= 64) return null;

  const sha = text.substring(0, 16);
  const md51 = text.substring(16, 32);
  const key = text.substring(32, 48);
  const md52 = text.substring(48, 64);
  const md5 = md51 + md52;
  const encrypt = text.substring(64);
  if (CryptoJS.MD5(sha + encrypt + key).toString() !== md5.toLowerCase()) {
    throw new Error("数据已被篡改！")
  }

  return decryptWith(encrypt, key);
}

export const decryptWith = (encrypt, key) => {
  const uKey = CryptoJS.enc.Utf8.parse(key);
  const iv = CryptoJS.enc.Utf8.parse();
  const decrypt = CryptoJS.AES.decrypt(encrypt, uKey, {
    iv: iv,
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  })
  return CryptoJS.enc.Utf8.stringify(decrypt);
}

export const aesDecrypt = (token, sha) => {
  if (sha.length <= 16) return '';

  const base64 = CryptoJS.enc.Base64.parse(token);
  const src = CryptoJS.enc.Base64.stringify(base64);

  const key = CryptoJS.enc.Utf8.parse(sha.substr(0, 16));
  const iv = CryptoJS.enc.Utf8.parse();

  const decrypt = CryptoJS.AES.decrypt(src, key, {
    iv: iv,
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  })

  return CryptoJS.enc.Utf8.stringify(decrypt);
};

export default {
  encrypt,
  decrypt,
  aesDecrypt
};